<template>
  <div class="app-container">
    <!-- 基础信息 -->
    <h5 class="titleInfo">基础信息</h5>

    <el-form ref="form"  :rules="rules" :model="form" label-width="130px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="realname">
            <el-input v-model="form.realname" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="username">
            <el-input v-model="form.username" readonly />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="级别" prop="roleId">
            <el-select v-model="form.roleId" placeholder="请选择">
              <el-option
                v-for="(item,index) in roleOption"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="加盟金额" prop="money">
            <el-input v-model="form.money" @blur="moneyFn(form.money)" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="交钱分公司" prop="payBranchId">
            <el-select v-model="form.payBranchId" placeholder="请选择">
              <el-option
                v-for="item in payOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="账户类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择">
              <el-option
                v-for="item in typeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="招商地区" prop="province">
            <el-cascader v-model="selectedOptions" :options="options" @change="pcaList" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合同时间">
            <el-date-picker
              v-model="form.signTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="签约类型" prop="signType">
            <el-radio v-model="form.signType" :label="1">赠送</el-radio>
            <el-radio v-model="form.signType" :label="2">购买</el-radio>
          </el-form-item>
        </el-col>
        <el-col v-if="form.type==4" :span="12">
          <el-form-item label="考虑开始时间" prop="thinkStartTime">
            <el-date-picker
              v-model="form.thinkStartTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.type==4" :span="12">
          <el-form-item label="考虑结束时间" prop="thinkEndTime">
            <el-date-picker
              v-model="form.thinkEndTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="form.type==4" :span="12">
          <el-form-item label="试用时间" prop="trialEndTime">
            <el-date-picker
              v-model="form.trialEndTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间"
              :picker-options="pickerOptions"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 推荐人信息 -->
      <div class="divBar" />
      <h5 class="titleInfo">推荐人信息</h5>

      <el-row>
        <el-col :span="12">
          <el-form-item label="推荐人姓名" prop="referUser">
            <!-- <span v-if="list1.refereeName" class="spanToInput">{{list1.refereeName | filterNull}}</span> -->
            <el-input v-model="form.referUser" :disabled="isrefereeName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="推荐人手机号" prop="referUserPhone">
            <!-- <span v-if="list1.referee" class="spanToInput">{{list1.referee| filterNull}}</span> -->
            <el-input v-model="form.referUserPhone" :disabled="isrefereeName" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 实名认证信息 -->
      <div class="divBar" />
      <h5 class="titleInfo">实名认证信息</h5>

      <el-row v-if="list1">
        <el-col :span="12">
          <el-form-item label="证件类型">
            <span v-if="userIdentityAuth.length>0" class="spanToInput">
              <span
                v-for="(i,index) in userIdentityAuth"
                :key="index"
              >{{ i.identityType | cardNull }}</span>
            </span>
            <el-select v-else v-model="form.idCardType" placeholder="请选择">
              <el-option
                v-for="item in cardOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="证件号码">
            <span v-if="userIdentityAuth.length>0" class="spanToInput">
              <span v-for="(i,index) in userIdentityAuth" :key="index">{{ i.identity | filterNull }}</span>
            </span>
            <el-input v-else v-model="form.idCard" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 银行卡信息 -->
      <div class="divBar" />
      <h5 class="titleInfo">银行卡信息</h5>

      <el-row v-for="(val,index) in list2" :key="index">
        <el-col :span="12">
          <el-form-item label="开户行">
            <span class="spanToInput">{{ val.bankName | filterNull }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="银行卡号">
            <span class="spanToInput">{{ val.cardNumber | filterNull }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="list2.length==0">
        <el-col :span="12">
          <el-form-item label="开户行" prop="banksDTOListName">
            <el-input v-model="form.banksDTOListName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="银行卡号" prop="banksDTOListCard">
            <el-input v-model="form.banksDTOListCard" />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 联创信息 -->
      <div v-if="form.type==7">
        <div class="divBar" />
        <h5 class="titleInfo">联创信息</h5>
        <el-row>
          <el-col :span="12">
            <el-form-item label="推荐渠道" :prop="form.type==7?'recommendId':''">
              <el-select v-model="form.recommendId" placeholder="请选择">
                <el-option
                  v-for="item in payOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生效时间" :prop="form.type==7?'takeEffectTime':''">
              <el-date-picker
                v-model="form.takeEffectTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                placeholder="选择日期时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="认购分公司" :prop="form.type==7?'subscriptionId':''">
              <el-select v-model="form.subscriptionId" placeholder="请选择">
                <el-option
                  v-for="(item, index) in provinceOfficeList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="认购金额" :prop="form.type==7?'subscriptionAmount':''">
              <el-input v-model="form.subscriptionAmount" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上传合同" :prop="form.type==7?'contractImg':''">
              <newUpload
                ref="contractImg"
                type="file"
                :file-list="contractImg"
                :file-num="5"
                accept="jpeg、JPG、jpg、png"
              />
              <p>请上传合同，最多允许上传5个附件，支持格式：jpeg、JPG、jpg、png</p>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <el-form-item>
        <el-button style="margin:30px 0" type="primary" @click="submitFn('form')" :loading="isdata">立即提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { provinceOfficeList } from '@/api/provinceOfficeList'
import { vipInfo } from '@/api/vipInfo'
import { companyList } from '@/api/branchOfficeDropDown'
import { joinFacilitator } from '@/api/joinFacilitator'
import newUpload from '@/components/imgUpload/index'
// 手机号正则
const phoneReg = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入会员手机号'))
  } else {
    const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    if (reg.test(value)) {
      callback()
    } else {
      return callback(new Error('手机格式错误'))
    }
  }
}
export default {
  name: 'JoinFacilitator',
  components: {
    newUpload
  },
  filters: {
    filterNull(e) {
      if (!e) {
        return '暂无'
      } else {
        return e
      }
    },
    cardNull(e) {
      return window.helper.cardType(String(e))
    }
  },
  data() {
    return {
      isdata:false,
      provinceOfficeList: [],
      dates: '',
      contractImg: [],
      form: {
        contractImg: [],
        value: '',
        signType: '',
        businessAccountType: '',
        banksDTOListName: '',
        banksDTOListCard: '',
        userId: '',
        createdBy: 0,
        realname: '',
        username: '',
        roleId: null,
        money: '',
        payBranchId: '',
        type: null,
        province: '',
        city: '',
        area: '',
        signTime: null,
        thinkStartTime: null,
        thinkEndTime: null,
        trialEndTime: null,
        referUser: '',
        referUserPhone: '',
        idCardType: '',
        idCard: '',
        banksDTOList: [
          {
            name: '',
            card: ''
          }
        ]
      },
      rules: {
        contractImg: [
          {
            required: true,
            message: '上传合同图片',
            trigger: 'blur'
          }
        ],
        signType: [
          { required: true, message: '请输入签约类型', trigger: 'blur' }
        ],
        recommendId: [
          { required: true, message: '请输入推荐渠道分公司ID', trigger: 'blur' }
        ],
        subscriptionId: [
          { required: true, message: '请输入认购分公司ID', trigger: 'blur' }
        ],
        subscriptionAmount: [
          { required: true, message: '请输入认购金额', trigger: 'blur' }
        ],
        takeEffectTime: [
          { required: true, message: '请输入生效时间', trigger: 'blur' }
        ],
        realname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        username: [{ required: true, trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择级别', trigger: 'blur' }],
        money: [{ required: true, message: '请输入加盟金额', trigger: 'blur' }],
        payBranchId: [
          { required: true, message: '请选择交钱分公司', trigger: 'blur' }
        ],
        type: [{ required: true, message: '请选择账户类型', trigger: 'blur' }],
        province: [
          { required: true, message: '请输入省市区', trigger: 'blur' }
        ],
        thinkStartTime: [
          { required: true, message: '请选择考虑开始时间', trigger: 'blur' }
        ],
        thinkEndTime: [
          { required: true, message: '请选择考虑结束时间', trigger: 'blur' }
        ],
        trialEndTime: [
          { required: true, message: '请选择试用时间', trigger: 'blur' }
        ],
        referUser: [
          { required: true, message: '请输入推荐人姓名', trigger: 'blur' }
        ],
        referUserPhone: [
          { required: true, validator: phoneReg, trigger: 'blur' }
        ],
        idCardType: [
          { required: true, message: '请选择证件类型', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '请输入证件号码', trigger: 'blur' }
        ],
        banksDTOListName: [
          { required: true, message: '请输入开户行', trigger: 'blur' }
        ],
        banksDTOListCard: [
          { required: true, message: '请输入银行卡号', trigger: 'blur' }
        ]
      },
      list1: {},
      list2: [],
      options: [],
      roleOption: [
        // {
        //   value: "1",
        //   label: "普通用户"
        // },
        {
          value: '2',
          label: '特约授权经销商'
        },
        {
          value: '3',
          label: '高级授权经销商'
        },
        {
          value: '7',
          label: '普通合伙人授权经销商'
        },
        {
          value: '8',
          label: '高级合伙人授权经销商'
        }
      ],
      payOption: [],
      cardOption: [],
      typeOption: [],
      selectedOptions: [],
      userIdentityAuth: [],
      isrefereeName: false
    }
  },
  watch: {
    // 'form.roleId'(val) {
    //   if (val !== '2') {
    //     this.form.type = ''
    //   }
    // },
    // 'form.type'(val) {
    //   if (val == '4') {
    //     this.form.roleId = '2'
    //     this.form.type = '4'
    //   }
    // }
  },
  mounted() {
    this.form.userId = Number(this.$route.query.userId)
    console.log(this.$route.query.type)
    this.form.businessAccountType = this.$route.query.type
    this.form = JSON.parse(JSON.stringify(this.form))
    this.getList()
    // 省市区数据获取
    var addData = require('../../../../static/address/area.json')
    this.options = addData
    // 分公司列表
    this.getCompanyList()
    // 账户类型
    this.typeOption = window.helper.accountType('listReturn')
    // 身份证类型
    this.cardOption = window.helper.cardType('listReturn')
    // 角色
    // this.roleOption = window.helper.roleFn("listReturn");
  },
  methods: {
    // 数字校验
    moneyFn(e) {
      const reg = new RegExp('^[0-9]*$')
      if (!reg.test(e)) {
        this.form.money = 0
      }
    },
    // typeChange(){
    //     console.log(666)
    //     if(this.form.roleId!="2"){
    //         this.form.type = ""
    //     }
    //     if(this.form.type=="4"){
    //         this.form.roleId = "2"
    //         this.form.type = "4"
    //     }
    // },
    // 省市区数据改变
    pcaList(value) {
      let e = this.selectedOptions
      e = value
      this.form.province = e[0]
      this.form.city = e[1]
      this.form.area = e[2]
    },
    // 获取数据
    getList() {
      const datas = { userId: this.form.userId }
      vipInfo(datas)
        .then()
        .then(res => {
          console.log(res.data.data)
          if (!res.data.code) {
            if (res.data.data.user) {
              this.list1 = res.data.data.user
            }
            if (res.data.data.bankCard) {
              this.list2 = res.data.data.bankCard
            }
            this.userIdentityAuth = res.data.data.userIdentityAuth
            this.form.realname = res.data.data.user.realname
              ? res.data.data.user.realname
              : ''
            this.form.username = res.data.data.user.username
            this.isrefereeName = !!res.data.data.user.refereeName
            this.form.referUser = res.data.data.user.refereeName
            this.form.referUserPhone = res.data.data.user.referee

            this.form.idCardType = res.data.data.userIdentityAuth[0]
              ? res.data.data.userIdentityAuth[0].identityType
              : null
            this.form.idCard = res.data.data.userIdentityAuth[0]
              ? res.data.data.userIdentityAuth[0].identity
              : null
            this.form = JSON.parse(JSON.stringify(this.form))

            const tf = this.form
            // 提交前对已有数据进行处理
            tf.referUser = this.list1.refereeName
            tf.referUserPhone = this.list1.referee
            // if (this.list1.identityType != [null]) {
            //   tf.idCardType = this.list1.identityType;
            // }
            // if (this.list1.identity != [null]) {
            //   tf.idCard = this.list1.identity;
            // }
            if (this.list2.length > 0) {
              this.form.banksDTOListName = ''
              this.form.banksDTOListCard = ''
            }
          } else {
            this.$message.error(res.data.msg)
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    // 获取分公司列表
    async getCompanyList() {
      companyList()
        .then(res => {
          const resData = res.data.data
          const newData = []
          resData.forEach(e => {
            newData.push({
              value: e.id,
              label: e.name
            })
          })
          this.payOption = newData
        })
        .catch(error => {
          this.$message.error(error)
        })
      const res = await provinceOfficeList({ types: [0] })
      if (res.data.code == 0) {
        this.provinceOfficeList = res.data.data
      } else {
        this.$message.error(res.data.msg)
      }
    },
    // 提交
    submitFn(e) {
      console.log(this.form.type)
      if (this.form.type == 7) {
        this.form.contractImg = this.$refs.contractImg.submitUpload()
      }
      console.log(this.form.contractImg)
      this.$refs[e].validate(valid => {
        // console.log(valid);
        if (valid) {
          //   this.form.type = Number(this.form.type);
          //   this.form.roleId = Number(this.form.roleId);
          //   this.form.money = Number(this.form.money);
          const datas = { ...this.form }
          datas.type = Number(datas.type)
          datas.roleId = Number(datas.roleId)
          datas.money = Number(datas.money)
          // console.log(JSON.stringify(this.form));
          this.isdata = true
          joinFacilitator(datas)
            .then()
            .then(res => {
              this.isdata = false
              // console.log(res)
              if (!res.data.code) {
                this.$message({
                  message: '加入成功',
                  type: 'success'
                })
                this.$router.push('/vipIndex')
              } else {
                this.$message.error(res.data.msg)
              }
            })
            .catch(error => {
              this.$message.error(error)
            })
        } else {
          this.$message({
            message: '必填项不能为空',
            type: 'warning'
          })
        }
      })
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 0px !important;
}
</style>
